package top.igotcha.controller;

import com.aliyuncs.DefaultAcsClient;
import com.aliyuncs.exceptions.ClientException;
import com.aliyuncs.vod.model.v20170321.DeleteVideoRequest;
import com.aliyuncs.vod.model.v20170321.GetVideoPlayAuthRequest;
import com.aliyuncs.vod.model.v20170321.GetVideoPlayAuthResponse;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import top.igotcha.commonutils.exception.GuliException;
import top.igotcha.service.VodService;
import top.igotcha.commonutils.utils.ConstantPropertiesUtils;
import top.igotcha.commonutils.utils.InitVodClient;
import top.igotcha.commonutils.utils.R;

import java.util.List;

@RestController
@RequestMapping("/eduvod/video")
//@CrossOrigin
public class VodController {

    @Autowired
    private VodService vodService;

    //上传头像的方法
    @PostMapping
    public R uploadVideo(MultipartFile file) {
        //获取上传文件  MultipartFile
        //返回上传到oss的路径
        String videoId = vodService.uploadVideo(file);
        return R.OK().data("videoId",videoId);
    }

    @DeleteMapping("{videoId}")
    public R removeAliYunVideo(@PathVariable String videoId){
        try {
            DefaultAcsClient client = InitVodClient.initVodClient(ConstantPropertiesUtils.ACCESS_KEY_ID, ConstantPropertiesUtils.ACCESS_KEY_SECRET);
            DeleteVideoRequest request = new DeleteVideoRequest();
            request.setVideoIds(videoId);
            client.getAcsResponse(request);
            return R.OK();
        } catch (ClientException e) {
            e.printStackTrace();
            throw new GuliException(20001,"删除失败");
        }
    }
    //定义调用的方法路径
    @DeleteMapping("deleteBatch")
    public R removeBatchAliYunVideo(@RequestParam("videoList") List<String> videoList){
        vodService.removeBatchAliYunVideo(videoList);
        return R.OK();
    }

    //根据视频id获取视频凭证
    @GetMapping("getPlayAuth/{id}")
    public R getPlayAuth(@PathVariable String id) {
        //System.out.println(id);
        try {
            //创建初始化对象
            DefaultAcsClient client =
                    InitVodClient.initVodClient(ConstantPropertiesUtils.ACCESS_KEY_ID, ConstantPropertiesUtils.ACCESS_KEY_SECRET);
            //创建获取凭证request和response对象
            GetVideoPlayAuthRequest request = new GetVideoPlayAuthRequest();
            //向request设置视频id
            request.setVideoId(id);
            //调用方法得到凭证
            GetVideoPlayAuthResponse response = client.getAcsResponse(request);
            String playAuth = response.getPlayAuth();
            return R.OK().data("playAuth",playAuth);
        }catch(Exception e) {
            throw new GuliException(20001,"获取凭证失败");
        }
    }
}
